package com.easipass.exangeservice.msg;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Set;
import java.util.Map.Entry;

/**
 * 
 * @version $Id$
 * @author itea
 * @date 2009-12-10
 */
public abstract class AbstractMsg implements Msg {

	protected HashMap<String, Object> attrs = new HashMap<String, Object>();

	public <T> T getAttribute(String key) {
		return (T) attrs.get(key);
	}

	public <T> void setAttribute(String attr, T value) {
		attrs.put(attr, value);
	}

	public void copyAttributesFrom(Msg msg) {
		for(Entry<String, Object> e : msg.getAttributes())
			attrs.put(e.getKey(), e.getValue());
	}

	public Set<Entry<String, Object>>  getAttributes() {
		return attrs.entrySet();
	}

	public String[] attributeNames() {
		return attrs.keySet().toArray(new String[0]);
	}

	public void removeAttribute(String attr) {
		attrs.remove(attr);
	}
	
	public static void copyRawData(RawMsg fromMsg, RawMsg toMsg, int size) throws IOException {
		InputStream in = fromMsg.openInputStream();
		OutputStream out = toMsg.openOutputStream();
		try {
			copyRawData(in, out, size);
		} finally {
			try {
				if(in != null) in.close();
			} finally {
				if(out != null) out.close();
			}
		}
	}
	
	public static void copyRawData(InputStream in, OutputStream out, int size) throws IOException {
		int idx = 0;
		byte[] buf = new byte[1024];
		int count = 0;
		while(true) {
			count = in.read(buf);
			if(count < 1) break; // end
			
			out.write(buf, 0, count);
			
			idx += count;
			if(idx == size) break; // end
		}
	}
	
}
